//
//  BJPictureFrameViewController.m
//  BowJoy
//
//  Created by  on 2024/5/16.
//

#import "BJPictureFrameViewController.h"
#import "BJPayCoinsPopView.h"
#import "BJRewardPopView.h"
#import "BJRewardAginPopView.h"
#import "BJAvatarFrameListCollectionViewCell.h"
#import "BJAvatarFrameModel.h"
#import "BJCoinStoreViewController.h"
@interface BJPictureFrameViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (weak, nonatomic) IBOutlet UIView *bgGroundView;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (weak, nonatomic) IBOutlet UIImageView *headerIcon;
@property (weak, nonatomic) IBOutlet UIImageView *headerBgIcon;

@property (weak, nonatomic) IBOutlet UIImageView *selectImage1;

@property (weak, nonatomic) IBOutlet UIImageView *selectImage2;

@property (weak, nonatomic) IBOutlet UIImageView *selectImage3;
@property (weak, nonatomic) IBOutlet UIImageView *selectImage4;
@property (weak, nonatomic) IBOutlet UILabel *nikeNameL;

@property (nonatomic,assign) NSInteger selectIndex;
@property (nonatomic,assign) NSInteger canUserIndex;

@property (weak, nonatomic) IBOutlet UIView *selectIcon1;

@property (weak, nonatomic) IBOutlet UIView *selectIcon2;

@property (weak, nonatomic) IBOutlet UIView *selectIcon3;
@property (weak, nonatomic) IBOutlet UIView *selectIcon4;
@property (nonatomic) NSInteger availableCoins;


@property (nonatomic,strong)NSMutableArray *dataList;

@end

@implementation BJPictureFrameViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.naviTitle = @"My Avatar frame";
    [self.headerIcon setImageURL:[NSURL URLWithString:[BJUserManager sharedManager].userInfoData.avatarUrl]];
    self.nikeNameL.text = [BJUserManager sharedManager].userInfoData.nickname;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applePaySuccess) name:kNotificationAppleSuccessfulPurchase object:nil];////商品购买(支付)成功通知

    [self requestMyCoin];
        
    UICollectionViewFlowLayout * layOut = [[UICollectionViewFlowLayout alloc]init];
    layOut.itemSize = CGSizeMake(100, 130);
    self.collectionView.collectionViewLayout = layOut;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.collectionView registerNib:[UINib nibWithNibName:@"BJAvatarFrameListCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"BJAvatarFrameListCollectionViewCell"];
    self.canUserIndex = [[[NSUserDefaults standardUserDefaults] objectForKey:KIsAvatarFrameKey] integerValue];
    NSString *iconPictureFrame =  [[NSUserDefaults standardUserDefaults] objectForKey:KSelectPictureFrameKey];
    NSString *last = [iconPictureFrame substringFromIndex:iconPictureFrame.length-1];//字符串结尾
    self.selectIndex = [last intValue];

    self.dataList = [[NSMutableArray alloc]init];
    for (int i = 0; i<4; i++) {
        BJAvatarFrameModel *model = [[BJAvatarFrameModel alloc]init];
        model.imageUrl = [NSString stringWithFormat:@"icon_play_PictureFrame%d",i];
        if ((i+1) == self.canUserIndex) {
            model.isCanUse = YES;
        }else{
            model.isCanUse = NO;
        }
        if ((i+1) == [last intValue]) {
            model.isSelect = YES;
            model.isBuy = YES;
            self.headerBgIcon.image = [UIImage imageNamed:[NSString stringWithFormat:@"icon_PictureFrame%ld",(long)self.selectIndex]];
        }else{
            model.isSelect = NO;
        }
        [self.dataList addObject:model];
    }
    
    [self.collectionView reloadData];
    
    
}

#pragma mark --UICollectionViewDelegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return  self.dataList.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID=@"BJAvatarFrameListCollectionViewCell";
    BJAvatarFrameListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.model = self.dataList[indexPath.row];
   
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    BJAvatarFrameModel*model = self.dataList[indexPath.row];
    
    if (model.isCanUse) {
        if (model.isBuy) {
            model.isSelect = !model.isSelect;
            if (model.isSelect) {
                self.selectIndex = indexPath.row+1;
                self.headerBgIcon.image = [UIImage imageNamed:[NSString stringWithFormat:@"icon_PictureFrame%ld",(long)indexPath.row+1]];
            }else{
                self.selectIndex = 0;
                self.headerBgIcon.image = [UIImage imageNamed:@""];
            }
            [self.collectionView reloadData];
        }else{

            BJPayCoinsPopView *payCoinsView = [[BJPayCoinsPopView alloc]initWithTitle:@"Would you be willing to spend 39 coins to purchase this profile picture frame"];
            [payCoinsView setUpdateOKBack:^{
                if (self.availableCoins<39) {
                    BJRewardAginPopView *rewardAginPopView = [[BJRewardAginPopView alloc]initWithTitle:@"Mistake" andContent:@"You don't have enough coins, go recharge now"];
                    [rewardAginPopView setUpdateOKBack:^{
                        BJCoinStoreViewController *coinStoreView = [[BJCoinStoreViewController alloc]init];
                        [self.navigationController pushViewController:coinStoreView animated:YES];
                    }];
                    [rewardAginPopView showView];
                }else{
                    [[BJNetManager shareNetManager] postReviewModeConsumeWithOutlay:39 source:@"iap" completionHandler:^(id  _Nonnull responOj, NSError * _Nonnull error) {
                        NSDictionary *dict = responOj;
                        NSInteger code = [dict[@"code"] integerValue];
                        if(code == 0){
                            BJRewardPopView *rewardPopView = [[BJRewardPopView alloc]initWithTitle:@"Congratulations" andContent:@"Congratulations on getting a new avatar frame"];
                            [rewardPopView setUpdateOKBack:^{
                                model.isSelect = YES;
                                model.isBuy = YES;
                                self.selectIndex = indexPath.row+1;
                                [self.collectionView reloadData];
                                self.headerBgIcon.image = [UIImage imageNamed:[NSString stringWithFormat:@"icon_PictureFrame%ld",(long)indexPath.row+1]];
                            }];
                            [rewardPopView showView];
                        }else{
                            NSString *msg = dict[@"msg"];
                            [ASHUD showWithText:msg afterDelay:2];
                        }
                    }];
                }
            }];
            [payCoinsView showView];
        }
    }
}


-(void)requestMyCoin{
    kWeakSelf(weakSelf)
    [[BJNetManager shareNetManager]getUserCurrentCoinsWithcompletionHandler:^(BJUserCoinsModel * _Nonnull model, NSError * _Nonnull error) {
        if(!error){
            weakSelf.availableCoins = model.data.availableCoins;
        }
    }];
}

-(void)applePaySuccess{
    [self requestMyCoin];
}


- (IBAction)clickSaveBtn:(id)sender {
    if (self.canUserIndex!=0&&self.selectIndex!=0) {
        [ASHUD showWithText:@"save successfully" afterDelay:1];
        [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"icon_PictureFrame%ld",(long)self.selectIndex] forKey:KSelectPictureFrameKey];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self.updateUserHeaderImage) {
                self.updateUserHeaderImage();
            }
            [self.navigationController popViewControllerAnimated:YES];
        });
    }else{
        [ASHUD showWithText:@"Please select your profile picture frame！" afterDelay:1];

    }

}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
